package view;

import controller.CiudadController;
import controller.PerfilController;
import controller.UsuarioController;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.swing.JOptionPane;
import model.Ciudad;
import model.Perfil;
import model.Usuario;
import util.GenerarPassword;
import util.MaxLengthTextDocument;

public class AgregarUsuario extends javax.swing.JFrame {

    PerfilController perfilController = new PerfilController();
    CiudadController ciudadController = new CiudadController();
    UsuarioController usuarioController = new UsuarioController();

    public AgregarUsuario() {
        initComponents();
        iniciaCampos();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtNombres = new javax.swing.JTextField();
        txtApePat = new javax.swing.JTextField();
        txtApeMat = new javax.swing.JTextField();
        txtDNI = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        cmbPerfil = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Agregar Usuario");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel1.setText("Nombres: (*)");

        jLabel2.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel2.setText("Apellido Paterno: (*)");

        jLabel3.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel3.setText("Apellido Materno: (*)");

        jLabel4.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel4.setText("DNI: (*)");

        jLabel5.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel5.setText("Email: (*)");

        txtEmail.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N

        btnAceptar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/aceptar.png"))); // NOI18N
        btnAceptar.setText("Aceptar");
        btnAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAceptarMouseClicked(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        txtNombres.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtNombres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombresKeyTyped(evt);
            }
        });

        txtApePat.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtApePat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApePatKeyTyped(evt);
            }
        });

        txtApeMat.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtApeMat.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApeMatKeyTyped(evt);
            }
        });

        txtDNI.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txtDNI.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDNIKeyTyped(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel6.setText("Perfil: (*)");

        cmbPerfil.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(55, 55, 55)
                .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel2)
                .addGap(20, 20, 20)
                .addComponent(txtApePat, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(txtApeMat, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel4)
                .addGap(82, 82, 82)
                .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel5)
                .addGap(74, 74, 74)
                .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel6)
                .addGap(74, 74, 74)
                .addComponent(cmbPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addComponent(btnAceptar)
                .addGap(18, 18, 18)
                .addComponent(btnCancelar))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel1))
                    .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel2))
                    .addComponent(txtApePat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel3))
                    .addComponent(txtApeMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel4))
                    .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel5))
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel6))
                    .addComponent(cmbPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar)))
        );

        setSize(new java.awt.Dimension(352, 295));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtNombresKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombresKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (Character.isSpaceChar(vChar))
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNombresKeyTyped

    private void txtApePatKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApePatKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (Character.isSpaceChar(vChar))
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtApePatKeyTyped

    private void txtApeMatKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtApeMatKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isAlphabetic(vChar)
                || (Character.isSpaceChar(vChar))
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtApeMatKeyTyped

    private void txtDNIKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDNIKeyTyped
        char vChar = evt.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDNIKeyTyped

    private void btnAceptarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAceptarMouseClicked

        Usuario usuario = new Usuario();

        if ("".equals(txtNombres.getText())
                || "".equals(txtApePat.getText())
                || "".equals(txtApeMat.getText())
                || "".equals(txtDNI.getText())
                || "".equals(txtEmail.getText())) {

            JOptionPane.showMessageDialog(null, "Por favor complete los campos obligatorios", "Faltan Datos", JOptionPane.ERROR_MESSAGE);
        } else {
            boolean correoValido = validaCorreo(txtEmail.getText());
            if (!correoValido) {
                JOptionPane.showMessageDialog(null, "Por favor introduzca un correo válido", "Correo inválido", JOptionPane.ERROR_MESSAGE);
            } else {
                int existeUsuario = usuarioController.buscarUsuarioxDNI(txtDNI.getText());
                if (existeUsuario == 1) {
                    JOptionPane.showMessageDialog(null, "El DNI del usuario ya existe", "Usuario inválido", JOptionPane.ERROR_MESSAGE);
                } else {

                    Ciudad ciud = ciudadController.buscarCiudadxNombre("Lima");
                    Perfil perf = new Perfil();

                    if (cmbPerfil.getSelectedIndex() < 0) {
                        cmbPerfil.setSelectedItem(0);
                    }

                    String nombPerfil = (String) cmbPerfil.getSelectedItem();
                    perf = perfilController.buscarPerfilxNombre(nombPerfil);

                    String nombUsu = obtenNombreUsuario(txtNombres.getText(), txtApePat.getText(), txtApeMat.getText());
                    usuario.setNombres(txtNombres.getText());
                    usuario.setApPaterno(txtApePat.getText());
                    usuario.setApMaterno(txtApeMat.getText());
                    usuario.setDni(txtDNI.getText());
                    usuario.setEmail(txtEmail.getText());
                    usuario.setEstado("Activo");
                    usuario.setUsuario(nombUsu);
                    usuario.setCiudad(ciud);
                    usuario.setPerfil(perf);
                    usuario.setPassword(GenerarPassword.getPassword(
                            GenerarPassword.MINUSCULAS
                            + GenerarPassword.MAYUSCULAS, 8));

                    int resultado = usuarioController.agregarUsuario(usuario);

                    if (resultado == 1) {
                        JOptionPane.showMessageDialog(null, "Usuario Registrado Correctamente\n Nombre de usuario: " + nombUsu, "Éxito", JOptionPane.INFORMATION_MESSAGE);
                        this.dispose();
                        new Menu().setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(null, "Usuario No Registrado", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        }
    }//GEN-LAST:event_btnAceptarMouseClicked

    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        this.dispose();
        new Menu().setVisible(true);
    }//GEN-LAST:event_btnCancelarMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AgregarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AgregarUsuario().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbPerfil;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField txtApeMat;
    private javax.swing.JTextField txtApePat;
    private javax.swing.JTextField txtDNI;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtNombres;
    // End of variables declaration//GEN-END:variables

    private void iniciaCampos() {

        List<Perfil> lstPerfiles = perfilController.buscarTodosPerfiles(null);
        for (int i = 0; i < lstPerfiles.size(); i++) {
            cmbPerfil.addItem(lstPerfiles.get(i).getNombre());
        }

        MaxLengthTextDocument maxNom = new MaxLengthTextDocument();
        MaxLengthTextDocument maxApPat = new MaxLengthTextDocument();
        MaxLengthTextDocument maxApMat = new MaxLengthTextDocument();
        MaxLengthTextDocument maxDNI = new MaxLengthTextDocument();
        MaxLengthTextDocument maxEmail = new MaxLengthTextDocument();
        MaxLengthTextDocument maxPass = new MaxLengthTextDocument();

        maxNom.setMaxChars(15);
        maxApPat.setMaxChars(20);
        maxApMat.setMaxChars(20);
        maxDNI.setMaxChars(9);
        maxEmail.setMaxChars(35);
        maxPass.setMaxChars(10);

        txtNombres.setDocument(maxNom);
        txtApePat.setDocument(maxApPat);
        txtApeMat.setDocument(maxApMat);
        txtDNI.setDocument(maxDNI);
        txtEmail.setDocument(maxEmail);
    }

    private boolean validaCorreo(String email) {
        boolean result = true;
        try {
            InternetAddress emailAddr = new InternetAddress(email);
        } catch (AddressException ex) {
            return false;
        }
        return result;
    }

    private String obtenNombreUsuario(String nombre, String apel1, String apel2) {
        String nombUsuario = null;
        String nomMin = null;
        String apeMin = null;
        String primLet = null;

        nomMin = nombre.toLowerCase();
        apeMin = apel1.toLowerCase();

        primLet = nomMin.substring(0, 1);
        nombUsuario = primLet.concat(apeMin);

        if (nombUsuarioValido(nombUsuario) == 0) {
            apeMin = apel2.toLowerCase();
            primLet = apeMin.substring(0, 1);
            nombUsuario = nombUsuario.concat(primLet);
        }
        return nombUsuario;
    }

    private int nombUsuarioValido(String nombUsuario) {
        UsuarioController usuarioController = new UsuarioController();

        Usuario usu = usuarioController.buscaUsuarioxNombUsuario(nombUsuario);
        if (usu != null) {
            return 0;
        } else {
            return 1;
        }
    }
}
